package tech.eyao.hs60x.manager;

import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import tech.eyao.hs60x.common.ConstantsKey;
import tech.eyao.hs60x.dao.AccountDao;
import tech.eyao.hs60x.token.Token;
import tech.eyao.hs60x.utils.TokenUtils;

@Component
public class SignManager {
	@Resource
	private RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	private AccountDao accountDao;
	
	public boolean verify(String clientToken) {
		try {
			Token token = TokenUtils.parseToken(clientToken);
			if(null == token || token.getUserId() == 0 || StringUtils.isEmpty(token.getDeviceId())) {
				return Boolean.FALSE;
			}
			// 查询token
			String tokenValue = redisTemplate.opsForValue().get(ConstantsKey.getUserTokenKey(token.getUserId()));
			if(StringUtils.isNotEmpty(tokenValue) && clientToken.equalsIgnoreCase(tokenValue)) {
				return Boolean.TRUE;
			}
		} catch (Exception e) {
			return Boolean.FALSE;
		}
		return Boolean.FALSE;
	}
	
	public boolean checkAccount(String token) {
		Long userId = TokenUtils.getUserId(token);
		if(null != userId && null != accountDao.selectByPrimaryKey(userId)) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}
}
